//
//  YZStateBtn.m
//  VET
//
//  Created by Lam BG on 2018/6/29.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZStateBtn.h"

@interface YZStateBtn()

@property (nonatomic, strong) UIImage *normalImg;
@property (nonatomic, strong) UIImage *switchImg;

@end

@implementation YZStateBtn

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setupRACObserve];
    }
    
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    self = [super initWithCoder:aDecoder];
    if (self) {
        
        [self setupRACObserve];
    }
    
    return self;
}

- (void)setupRACObserve {
    
    [self bindRAC];
    [self addTarget:self action:@selector(tap:) forControlEvents:(UIControlEventTouchUpInside)];
}


- (void)setStateImage:(UIImage*)normalImg withSwitchImage:(UIImage*)switchImg {
    
    self.normalImg = normalImg;
    self.switchImg = switchImg;
    
    [self setImage:[normalImg imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:UIControlStateNormal];
}

- (void)bindRAC {
    
    // 绑定状态切换
    @weakify(self)
    [RACObserve(self, isSwitch) subscribeNext:^(id switchFlag) {
        
        @strongify(self)
        BOOL isSwitch = [switchFlag boolValue];
        if (isSwitch) {
            if (self.switchImg) {
                
                [self setImage:[self.switchImg imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:UIControlStateNormal];
            }
        } else {
            if (self.normalImg) {
                
                [self setImage:[self.normalImg imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:UIControlStateNormal];
            }
        }
    }];
}

- (void)dealloc {
    
    NSLog(@"YZStateBtn dealloc");
}

#pragma mark - event actions

- (void)tap:(id)sender {
    
    self.isSwitch = !self.isSwitch;
}



@end
